<template>
  <!-- 商家信息  -->
  <van-row style="padding-top:10px;padding-bottom:10px;background-color: beige;box-sizing: border-box;">
      <van-col span="8" offset="2">
          <img :src="business.businessImg" style="width: 100%;"/>
      </van-col>
      <van-col span="12" offset="2">
          <div>商家名称：{{business.businessName}}</div>
          <div>商家简介：{{business.businessExplain}}</div>
          <div>商家地址：{{business.businessAddress}}</div>
          <van-row>
            <van-col span="10" offset="14" align="center">
              <!-- 购物车图标  在图标库网站里复制即可 -->
              <svg @click="showCart" style="margin-top: 10px;" 
              t="1732848317898" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="35556" width="32" height="32"><path d="M1013.318 283.028c-5.165-7.135-13.437-11.373-22.256-11.373h-764.063l-52.463-219.533c-2.956-12.366-14.006-21.082-26.714-21.082h-115.701c-15.168 0-27.465 12.285-27.465 27.465 0 15.182 12.295 27.465 27.465 27.465h94.028l168.638 705.673c-41.965 12.96-72.751 51.654-72.751 97.817 0 56.727 46.141 102.86 102.845 102.86 56.714 0 102.854-46.133 102.854-102.86 0-17.387-4.749-33.531-12.397-47.903h244.8c-7.65 14.373-12.397 30.516-12.397 47.903 0 56.727 46.141 102.86 102.854 102.86 56.707 0 102.845-46.133 102.845-102.86 0-56.701-46.141-102.833-102.845-102.833h-400.531l-12.252-51.257h518.265c11.847 0 22.362-7.591 26.077-18.857l134.986-408.785c2.769-8.369 1.347-17.569-3.822-24.703zM750.595 841.557c26.419 0 47.917 21.484 47.917 47.903s-21.498 47.93-47.917 47.93c-26.426 0-47.922-21.51-47.922-47.93-0.001-26.419 21.497-47.903 47.922-47.903zM372.809 889.461c0 26.419-21.498 47.93-47.922 47.93-26.419 0-47.917-21.51-47.917-47.93 0-26.419 21.498-47.903 47.917-47.903 26.426 0 47.922 21.484 47.922 47.903z" fill="#d81e06" p-id="35557"></path></svg>
            </van-col>
          </van-row>
      </van-col>
  </van-row>
 <van-row style="margin-top: 10px;">
  <van-col span="24">
    <!-- 查询餐品信息 -->
      <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="getFoodByBid"
        >
          <!-- 列表项 -->
          <van-row style="margin-top: 5px"  v-for="food in foodList" :key="food.foodId">
            <van-col :span="8" align="center" >
                <img :src="food.foodImg" style="width: 60%;height: 60px;">
            </van-col>
            <van-col :span="13" align="left" >
                <div style="font-size: 16px;">{{food.foodName}}</div>
                <div style="font-size: 12px;">￥{{food.foodPrice}}</div>
                <div style="font-size: 12px;">{{food.foodExplain}}</div>
            </van-col>
            <van-col :span="3" align="center" style="margin-top: 40px;">
              <!-- 点击该图标可以将餐品加入购物车 
                  foodId(需要通过点击的图标获取到所在行的餐品id)
                  businessId(从商家页面跳转过来时传递的)
                  userId(用户登录之后可以从本地存储来获取)
              -->
              <svg @click="addToCart(food.foodId)"  t="1732846529248" class="cartIcon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="31196" width="16" height="16"><path d="M962.079334 545.28l61.44-352.768c1.536-7.68-0.512-14.848-5.632-20.992-5.12-5.632-12.288-9.216-19.456-9.216H279.583334c-14.336 0-25.6 11.264-25.6 25.6s11.264 25.6 25.6 25.6h688.64l-53.248 304.128-631.296 84.48L184.351334 137.728c-1.536-7.68-6.656-14.336-13.824-17.408l-133.632-66.56c-12.8-6.144-28.16-1.024-34.304 11.776-6.144 12.8-1.024 28.16 11.776 34.304l122.368 60.416L266.271334 765.44c2.56 11.776 12.8 20.48 25.088 20.48h663.552c14.336 0 25.6-11.264 25.6-25.6s-11.264-25.6-25.6-25.6H311.839334l-17.408-81.92 645.632-86.016c11.264-2.048 19.968-10.752 22.016-21.504z" fill="#d81e06" p-id="31197"></path><path d="M395.295334 896m-51.2 0a51.2 51.2 0 1 0 102.4 0 51.2 51.2 0 1 0-102.4 0Z" fill="#d81e06" p-id="31198"></path><path d="M866.335334 896m-51.2 0a51.2 51.2 0 1 0 102.4 0 51.2 51.2 0 1 0-102.4 0Z" fill="#d81e06" p-id="31199"></path></svg>
            </van-col>
          </van-row>
      </van-list>
  </van-col>
</van-row>

<!-- 底部弹出 -->
  <van-popup
  v-model:show="showPopCart"
  position="bottom"
  :style="{ height: '70%' }"
  closeable
  close-icon="close"
  >
  <div>购物车</div>
  <van-card
      v-for="cartItem in cartList"
      :key="cartItem.cartId"
      :num="cartItem.quantity"
      :price="cartItem.food.foodPrice"
      :desc="cartItem.food.foodExplain"
      :title="cartItem.food.foodName"
      :thumb="cartItem.food.foodImg"
  >
  <!-- <template #tags>
      <van-tag plain type="primary">标签</van-tag>
      <van-tag plain type="primary">标签</van-tag>
  </template> -->
  <template #footer>
      <van-button size="mini" @click="jian(cartItem)">-</van-button>
      <van-button size="mini" @click="jia(cartItem)">+</van-button>
  </template>
  </van-card>

  <van-submit-bar :price="allPrice*100" button-text="提交订单" @submit="addOrder">
      <template #tip>
          <span v-if="chosenAddress">
              {{chosenAddress.contactName}}|{{chosenAddress.contactTel}}|{{chosenAddress.address}},
          </span>
          <span v-else>
              请选择收货地址, 
          </span>
          <span @click="showAddress">查看地址</span>
      </template>
  </van-submit-bar>

</van-popup>


<!-- 显示地址 -->
<van-popup
  v-model:show="showPopAddress"
  position="bottom"
  :style="{ height: '70%' }"
  closeable
  close-icon="close"
  >
  
</van-popup>

</template>

<script setup>
import { ref,getCurrentInstance, onMounted, computed } from 'vue';
import {showNotify, showToast } from 'vant';
import store from '@/store';

const {proxy} = getCurrentInstance();

const loading = ref(false);  //加载的状态  查询之前置为true  查询完毕置为false
const finished = ref(false);  //所有的数据全部查完之后置为true

const bid = ref(null);  //商家id值

const foodList = ref([]);  //当前商家的所有餐品

//根据商家id查询餐品列表
const getFoodByBid = ()=>{

      if(!bid.value){
          showNotify({ message: '无商家编号无法查询' });
          return;
      }

      loading.value = true;

      proxy.$axios({
        method: 'get',
        url: '/food/business/'+bid.value
      }).then(res=>{
        let resultBean = res.data;
        if(resultBean.code == 200){
          foodList.value = resultBean.data;

          loading.value = false;
          finished.value = true;

        }else{
          showNotify({ message: resultBean.msg });
        }
      }).catch(error=>{
        showNotify({ message: error.message });
      })
  }

/*
  当前商家对象  调用 getBusinessById 函数之后会给这个对象赋值
*/
const business = ref({});

/*
  通过商家id查询商家信息
*/
const getBusinessById = ()=>{
  proxy.$axios({
        method: 'get',
        url: '/business/'+bid.value
      }).then(res=>{
        let resultBean = res.data;
        if(resultBean.code == 200){
          business.value = resultBean.data;
        }else{
          showNotify({ message: resultBean.msg });
        }
      }).catch(error=>{
        showNotify({ message: error.message });
      })
}

const addToCart = (foodId)=>{

  //准备传递给服务端的参数   购物车项
  let cartItem = {
      foodId: foodId,
      businessId: bid.value,
      userId: 1,
      quantity: 1
  }

  proxy.$axios({
        method: 'post',
        url: '/cart/save',
        data: cartItem
      }).then(res=>{
        let resultBean = res.data;
        if(resultBean.code == 200){
          showNotify({ message: '添加购物车成功' });
        }else{
          showNotify({ message: resultBean.msg });
        }
      }).catch(error=>{
        showNotify({ message: error.message });
      })
}

//购物车列表   
const cartList = ref([]);
//弹出层是否显示
const showPopCart = ref(false);

/**
 * 查询当前用户在当前的商家加入购物车的餐品信息
 */
const showCart = ()=>{
  proxy.$axios({
        method: 'get',
        url: '/cart/1/'+bid.value
      }).then(res=>{
        let resultBean = res.data;
        if(resultBean.code == 200){
          cartList.value = resultBean.data;
          showPopCart.value = true; //显示购物车弹出层
        }else{
          showNotify({ message: resultBean.msg });
        }
      }).catch(error=>{
        showNotify({ message: error.message });
      })
  getAddressById();
}

//选中的地址
const chosenAddress = ref(null);

//通过地址id查询地址信息
const getAddressById = ()=>{
  if(store.state.chosenAddressId){
      proxy.$axios({
          method: 'get',
          url: '/address/'+store.state.chosenAddressId
      }).then(res=>{
          let resultBean = res.data;
          if(resultBean.code == 200){
              chosenAddress.value =  resultBean.data;
          }
      })
  }
   
}

//点击购物车中的减号按钮
const jian = (cartItem)=>{
   cartItem.quantity -= 1;
   console.log('jian',cartItem);

   //如果数量减到0  进行删除操作
   if(cartItem.quantity == 0){
      proxy.$axios({
          method: 'delete',
          url: '/cartItem/'+cartItem.cartId
      }).then(res=>{
          let resultBean = res.data;
          if(resultBean.code == 200){
              showCart();//删除完成之后重新查询
          }else{
              showNotify({ message: resultBean.msg });
              cartItem.quantity += 1;  //删除失败恢复原状
          }
      }).catch(error=>{
          showNotify({ message: error.message });
      })
      return;
   }

   //发起修改请求
   proxy.$axios({
      method: 'post',
      url: '/cart/save',
      data: cartItem
   }).then(res=>{
      let resultBean = res.data;
      if(resultBean.code != 200){
          showNotify({ message: resultBean.msg });
          cartItem.quantity += 1; //失败之后数量恢复原状
      }
  }).catch(error=>{
      showNotify({ message: error.message });
  })
}

//点击购物车项中的加号   进行数量修改
const jia = (cartItem)=>{
  cartItem.quantity += 1;
  console.log('jia',cartItem);
  
  proxy.$axios({
      method: 'post',
      url: '/cart/save',
      data: cartItem
   }).then(res=>{
      let resultBean = res.data;
      if(resultBean.code != 200){
          showNotify({ message: resultBean.msg });
          cartItem.quantity -= 1; //操作失败数量恢复原状
      }
  }).catch(error=>{
      showNotify({ message: error.message });
  })
   
}

//购物车项的总金额
const allPrice = computed(()=>{
  let sum = 0;
  cartList.value.forEach(cartItem=>{
      sum += cartItem.food.foodPrice*cartItem.quantity;
  })
  return sum;
})


//下订单
const addOrder = ()=>{

  if(!store.state.chosenAddressId){
      proxy.$router.push("/main/address")
      return;
  }

  //拼凑Order对象
   //根据购物车列表生成订单详情
   let orderDetailList = []
   cartList.value.forEach(cartItem=>{
      orderDetailList.push({
          foodId: cartItem.foodId,
          quantity: cartItem.quantity
      });
   });

   let order = {
      userId: 1,
      businessId: bid.value,
      addressId: store.state.chosenAddressId,
      orderTotal: allPrice.value,
      orderDetailList: orderDetailList
   }

   console.log('下订单---------',order);

   proxy.$axios({
      method: 'post',
      url: '/order/add',
      data: order
   }).then(res=>{
      let resultBean = res.data;
      if(resultBean.code == 200){
          showNotify({ message: '下单成功' });
          cartList.value = []; //清空购物车  此处清除的只有前端  @Todo 应该发请求到服务端清空
          //关闭下方弹出的购物车小窗口
          showPopCart.value = false;
      }else{
          showNotify({ message: resultBean.msg });
      }
  }).catch(error=>{
      showNotify({ message: error.message });
  })

}

//展示地址
const showAddress = ()=>{
  proxy.$router.push("/main/address");
}



onMounted(()=>{
  console.log('*********',proxy.$route.params.bid);
  //接收路由传递的参数   商家的id值   用商家的id值查询这个商家所有的餐品
  bid.value = proxy.$route.params.bid;
  getBusinessById();
})

</script>

<style>
.cartIcon{
  cursor: pointer;
}
.cartIcon:hover{
  opacity: 0.6;
}
</style>